package com.caidanxiaoyuan.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import com.caidanxiaoyuan.model.pay.PayModel;
import com.caidanxiaoyuan.model.pay.PayUtil;
import com.caidanxiaoyuan.util.JsonUtil;
import com.caidanxiaoyuan.util.ResponseUtil;

@Controller
@CrossOrigin
@RequestMapping("/pay")
public class PayController {


	private String ALIPAY_GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?";
	
	private String ALI_INPUT_CHARSET = "utf-8";
	
	@RequestMapping("/aliwap")
	public String aliwap(PayModel reqInfo,HttpServletRequest request){
		request.setAttribute("e", reqInfo);
		return "pay/aliwap";
	}
	
	
	/**
	 * @throws Exception 
	 * 
	* @Description: 支付宝  
	* @author zealot
	* @param @param reqInfo
	* @param @param response 
	* @return void    
	* @version 创建时间：2017年3月2日 上午11:48:23  
	* @throws
	 */
	@RequestMapping("/pay")
	public void submit(PayModel reqInfo,HttpServletResponse response) throws Exception{
		if(reqInfo.getFee()!=null){
			//支付宝支付
			//封装请求数据，获取签名，并添加到集合
			Map<String, String> sPara = PayUtil.aliorganizeRequestPara(reqInfo);
			
			List<String> keys = new ArrayList<String>(sPara.keySet());
			
			StringBuffer sbHtml = new StringBuffer();
			
			//按照支付宝要求的格式拼接html
			sbHtml.append("<form id=\"payform\" name=\"payform\" action=\"" + ALIPAY_GATEWAY_NEW
	                + "_input_charset=" + ALI_INPUT_CHARSET + "\" method=\"post\">");
			
			for (int i = 0; i < keys.size(); i++) {
	            String name = (String) keys.get(i);
	            
	            String value = (String) sPara.get(name);
	
	            sbHtml.append("<input type=\"hidden\" name=\"" + name + "\" value=\"" + value + "\"/>");
	        }
			
			//submit按钮控件请不要含有name属性
	        sbHtml.append("<input type=\"submit\" value=\"" + "确认" + "\" style=\"display:none;\"></form>");
	        
	        sbHtml.append("<script>document.forms['payform'].submit();</script>");
			ResponseUtil.write(response, sbHtml);
		}
	}
}
